package com.wwk.phone.service.impl;

import com.wwk.phone.dao.ThingDao;
import com.wwk.phone.dao.UserDao;
import com.wwk.phone.entity.Thing;
import com.wwk.phone.entity.User;
import com.wwk.phone.entity.vo.ThingVo;
import com.wwk.phone.service.ThingService;
import com.wwk.phone.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (Thing)表服务实现类
 *
 * @author makejava
 * @since 2023-06-05 14:59:58
 */
@Service
public class ThingServiceImpl implements ThingService {
    @Resource
    private ThingDao thingDao;

    @Resource
    private UserDao userDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Thing queryById(Long id) {
        return this.thingDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param thing 实例对象
     * @return 实例对象
     */
    @Override
    public Thing insert(Thing thing) {
        thing.setCreateTime(new Date());
        thing.setUpdateTime(new Date());
        this.thingDao.insert(thing);
        return thing;
    }

    /**
     * 修改数据
     *
     * @param thing 实例对象
     * @return 实例对象
     */
    @Override
    public Thing update(Thing thing) {
        thing.setUpdateTime(new Date());
        this.thingDao.update(thing);
        return this.queryById(thing.getId());
    }

    /**
     * 取消通讯率事件
     *
     * @param cancelId
     * @return
     */
    @Override
    public boolean cancelById(Long cancelId) {
        Thing thing = queryById(cancelId);
        thing.setDelete(1);
        return update(thing) != null;
    }

    @Override
    public boolean competeById(Long thingId) {
        Thing thing = queryById(thingId);
        thing.setCompete(1);
        return update(thing) != null;
    }

    @Override
    public R pageThingCondition(Long begin, Long limit, ThingVo thingVo, String userId) {
        List<Thing> list = this.thingDao.pageThingCondition((begin - 1) * limit, limit, thingVo, userId);
        List<ThingVo> thingVoList = new ArrayList<>();
        //获取当前用户姓名
        User user = userDao.queryById(Long.valueOf(userId));
        String username = user.getUsername();
        for (Thing thing : list) {
            ThingVo thingVo1 = new ThingVo();
            BeanUtils.copyProperties(thing, thingVo1);
            thingVo1.setUserName(username);
            thingVoList.add(thingVo1);
        }
        //先随便写
        long total = thingDao.countByCondition(thingVo, userId);
        return R.ok().data("rows", thingVoList).data("total", total);
    }

    @Override
    public boolean addThing(ThingVo thingVo, String userId) {
        Thing thing = new Thing();
        BeanUtils.copyProperties(thingVo, thing);
        thing.setUserId(userId);
        thing.setCompete(0);
        thing.setDelete(0);
        return insert(thing) != null;
    }
}
